package servletUtenteReg;

import gestioneContesto.GestoreContesto;

import java.io.IOException;
import java.util.ArrayList;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logicaUtenteReg.GestoreRichiesteRemote;

/**
 * Servlet implementation class AccettaRichiesteServlet
 */
public class AccettaRicAmiciziaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private RequestDispatcher dispatcher;
	private GestoreContesto contesto;
	private final int OK = 2;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AccettaRicAmiciziaServlet() {

		super();
		contesto = new GestoreContesto();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			eseguiRichiesta(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			eseguiRichiesta(request, response);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void eseguiRichiesta(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException {

		GestoreRichiesteRemote gestore = contesto.getGestore(GestoreRichiesteRemote.class, "GestoreRichiesteRemote");

		String richiedente = request.getParameter("richiedente");
		String destinatario = request.getParameter("destinatario");
		String nome = request.getParameter("nome");
		String cognome = request.getParameter("cognome");

		gestore.processaRichiestaAmicizia(richiedente, destinatario, OK);

		ArrayList<String> lista = gestore.listaRicAmicizia(destinatario);

		if(lista != null) {

			for(int i = 0; i < lista.size(); i++) {

				request.setAttribute("el" + i, lista.get(i));

			}

			request.setAttribute("size", lista.size());

		}

		else {

			request.setAttribute("size", 0);

		}
		
		request.setAttribute("id", destinatario);
		request.setAttribute("nome", nome);
		request.setAttribute("cognome", cognome);
		dispatcher = request.getRequestDispatcher("RichiesteAmicizia.jsp");
		dispatcher.forward(request, response);

	}

}
